<template>
  <el-dialog
    :title="$t('msg.excel.roleDialogTitle')"
    :model-value="modelValue"
    @close="closed"
  >
    <el-tree
      ref="treeRef"
      :data="allPermission"
      show-checkbox
      node-key="id"
      check-strictly
      default-expand-all
      :props="defaultProps"
    ></el-tree>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closed">{{ $t('msg.universal.cancel') }}</el-button>
        <el-button type="primary" @click="onConfirm">{{
          $t('msg.universal.confirm')
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineProps, defineEmits, watch, ref, onMounted } from 'vue'
import { getPermissionList } from '@/api/permission'
import { rolePermission, distributePermission } from '@/api/role'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
const i18n = useI18n()
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true
  },
  roleId: {
    type: String,
    required: true
  }
})
watch(
  () => props.roleId,
  (cur) => {
    if (cur) getRolePermission()
  }
)
const defaultProps = {
  children: 'children',
  label: 'permissionName'
}
const treeRef = ref(null)
const getRolePermission = async () => {
  const checkedKeys = await rolePermission(props.roleId)
  treeRef.value.setCheckedKeys(checkedKeys)
}
const allPermission = ref([])
const reqPermissionList = async () => {
  allPermission.value = await getPermissionList()
  console.log(
    '🚀 ~ reqPermissionList ~ allPermission.value:',
    allPermission.value
  )
}
onMounted(reqPermissionList)
const emits = defineEmits(['update:modelValue'])

/**
  确定按钮点击事件
 */
const onConfirm = async () => {
  await distributePermission({
    roleId: props.roleId,
    permissions: treeRef.value.getCheckedKeys()
  })
  ElMessage.success(i18n.t('msg.role.updateRoleSuccess'))
  closed()
}
/**
 * 关闭
 */
const closed = () => {
  emits('update:modelValue', false)
}
</script>
